<script setup lang="ts">
import { reactive, onMounted, computed } from 'vue';
import { showToast, navigateTo } from '@tarojs/taro';
import { RectDown as AppNutIconRectDown, RectUp as AppNutIconRectUp } from '@nutui/icons-vue-taro';
import { getSysImgUrl } from '/@/utils/index';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { INDEX_TOTAL } from '/@/api/modules/workbench/workbench';
import { APP_MENU_HOMEPAGE_SAVE } from '/@/api/modules/base/app-menu-homepage';
import { APP_MENU_TREE, APP_MENU_HOMEPAGE_QUERY } from '/@/api/modules/base/app-menu';
import { QUERY_APP_FLOW_PATH_RECORD_COUNT } from '/@/api/modules/flow-path/flow-path';
import { scanMenu } from '/@/utils/scan';
const state = reactive<{
  /**
   * 是否编辑状态
   */
  isEdit: boolean;
  /**
   * 菜单树
   */
  menuTree: AppMenu.Dto[];
  /**
   * 首页统计数据
   */
  indexTotal: WorkbenchApi.IndexTotalResp;
  /**
   * 首页菜单
   */
  homepageMenuList: AppMenu.Dto[];
  /**
   * 显示所有首页菜单
   */
  showAllHomepageMenuList: boolean;
  /**
   * 当前登录权限编码（1-WEB端，2-后勤端，3-员工端）
   */
  currentRolePlatformCode: AppSysUserApi.LoginAppResp['currentRolePlatformCode'];
  /**
   * 我的审批-待审批数量
   */
  myApproveCount: number;
}>({
  isEdit: false,
  menuTree: [],
  indexTotal: {},
  homepageMenuList: [],
  showAllHomepageMenuList: false,
  currentRolePlatformCode: 3,
  myApproveCount: 0,
});

/**
 * @function 获取菜单项徽标值
 * @param forword
 */
function getMenuItemBadgeValue(forword: string) {
  if (!forword) return '';
  return (
    {
      '/pages/work-order/list/index': state.indexTotal.workOrderQuantity,
      '/pages/inspection/list/index': state.indexTotal.planTaskQuantity1,
      '/pages/maintenance/list/index': state.indexTotal.planTaskQuantity2,
      '/pages/cleaning/list/index': state.indexTotal.planTaskQuantity3,
      '/pages/alarm/list/index': state.indexTotal.msgAlarmQuantity,
      '/pages/msg/list/index': state.indexTotal.messageQuantity,
      '/pages/my-approve/list/index': state.myApproveCount,
    }[forword] || ''
  );
}

/**
 * @function 选择首页菜单
 * @param menuItem
 * @param idx
 */
function selectedHomepageMenuItem(menuItem: AppMenu.Dto, idx: number) {
  if (!state.isEdit && menuItem.forword && menuItem.jumpLogic === 1) {
    navigateTo({ url: menuItem.forword });
  } else if (!state.isEdit && menuItem.forword && menuItem.jumpLogic === 2) {
    window.location.href = menuItem.forword;
  } else if (state.isEdit) {
    state.homepageMenuList.splice(idx, 1);
  }
}

/**
 * @function 保存首页菜单
 * @param menuList
 */
function saveHomepageMenu(menuList: AppMenu.Dto[]) {
  APP_MENU_HOMEPAGE_SAVE({
    menuIds: menuList.map((item) => {
      return item.id;
    }),
    rolePlatform: state.currentRolePlatformCode,
  })
    .then(() => {
      APP_MENU_HOMEPAGE_QUERY({ comQuery: { page: 1, pageSize: 100 } }).then((res) => {
        state.homepageMenuList = res.dto || [];
        state.isEdit = false;
      });
    })
    .catch((err) => {
      showToast({
        title: err.comResp.err || err.comResp.tip,
        icon: 'error',
      });
    });
}

/**
 * @function 选择菜单
 * @param menuItem
 */
function selectedMenuItem(menuItem: AppMenu.Dto) {
  if (!state.isEdit && menuItem.forword && menuItem.jumpLogic === 1) {
    //如果是扫一扫功能直接用钉钉的扫一扫
    if (menuItem.name === '扫一扫') {
      scanMenu();
    } else {
      navigateTo({ url: menuItem.forword });
    }
  } else if (!state.isEdit && menuItem.forword && menuItem.jumpLogic === 2) {
    window.location.href = menuItem.forword;
  } else if (
    state.isEdit &&
    !state.homepageMenuList
      .map((item) => {
        return item.id;
      })
      .includes(menuItem.id)
  ) {
    state.homepageMenuList.push(menuItem);
  }
}

onMounted(() => {
  LOGIN_APP().then((res) => {
    state.currentRolePlatformCode = res.currentRolePlatformCode;
  });

  APP_MENU_HOMEPAGE_QUERY({ comQuery: { page: 1, pageSize: 7 } }).then((res) => {
    state.homepageMenuList = res.dto || [];
  });

  APP_MENU_TREE({}).then((res) => {
    state.menuTree = res.dto || [];
  });

  INDEX_TOTAL({}).then((res) => {
    state.indexTotal.workOrderQuantity = res.workOrderQuantity;
    state.indexTotal.planTaskQuantity1 = res.planTaskQuantity1;
    state.indexTotal.planTaskQuantity2 = res.planTaskQuantity2;
    state.indexTotal.planTaskQuantity3 = res.planTaskQuantity3;
    state.indexTotal.msgAlarmQuantity = res.msgAlarmQuantity;
    state.indexTotal.messageQuantity = res.messageQuantity;
  });

  QUERY_APP_FLOW_PATH_RECORD_COUNT({ myHandleStatus: '1' }).then((res) => {
    state.myApproveCount = res.totalCount || 0;
  });
});

const unreadCount = computed(() => {
  return (count: number | string) => {
    if (typeof count === 'number') {
      return count > 99 ? '99+' : count;
    }
    return count;
  };
});
</script>

<template>
  <view class="all-utils-v2 app-page--1">
    <app-navbar title="全部应用" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="all-utils-v2__homepage-menu-wrapper">
        <view class="all-utils-v2__homepage-menu-wrapper--header">
          <view class="all-utils-v2__homepage-menu-wrapper__title">
            <text>首页应用</text>
          </view>
          <view class="all-utils-v2__homepage-menu-wrapper--header-center">
            <view class="all-utils-v2__homepage-menu-wrapper--header-wrapper">
              <image
                v-for="item in state.homepageMenuList"
                :key="item.id"
                :src="getSysImgUrl(item.imgBase64, true)"
                class="all-utils-v2__homepage-menu-wrapper__header-menu-item-img"
              />
            </view>
            <app-nut-icon-rect-down
              v-if="!state.showAllHomepageMenuList"
              class="all-utils-v2__homepage-menu-wrapper__header-menu-icon"
              @click="
                () => {
                  state.showAllHomepageMenuList = true;
                }
              "
            />
            <app-nut-icon-rect-up
              v-else
              class="all-utils-v2__homepage-menu-wrapper__header-menu-icon"
              @click="
                () => {
                  state.showAllHomepageMenuList = false;
                }
              "
            />
          </view>
          <nut-button
            v-if="!state.isEdit"
            type="info"
            size="mini"
            @click="
              () => {
                state.isEdit = true;
                state.showAllHomepageMenuList = true;
              }
            "
          >
            编辑
          </nut-button>
          <nut-button
            v-else
            type="success"
            size="mini"
            @click="saveHomepageMenu(state.homepageMenuList)"
          >
            保存
          </nut-button>
        </view>
        <view class="all-utils-v2__homepage-menu-wrapper--body">
          <nut-grid
            v-if="
              state.showAllHomepageMenuList &&
              state.homepageMenuList &&
              state.homepageMenuList.length
            "
            column-num="4"
            :border="false"
          >
            <nut-grid-item
              v-for="(item, index) in state.homepageMenuList"
              :key="item.id"
              :text="item.name"
              @click="selectedHomepageMenuItem(item, index)"
            >
              <nut-badge
                :value="state.isEdit ? '-' : unreadCount(getMenuItemBadgeValue(item.forword))"
                :color="state.isEdit ? '#ddd' : '#ff3e3e'"
              >
                <nut-avatar shape="square" bg-color="transparent">
                  <image :src="getSysImgUrl(item.imgBase64, true)" />
                </nut-avatar>
              </nut-badge>
            </nut-grid-item>
          </nut-grid>
        </view>
      </view>
      <view
        v-for="groupItem in state.menuTree"
        :key="groupItem.id"
        class="all-utils-v2__module-wrapper"
      >
        <view class="all-utils-v2__module-title">{{ groupItem.name }}</view>

        <nut-grid
          v-if="groupItem.children && groupItem.children.length"
          column-num="4"
          :border="false"
        >
          <nut-grid-item
            v-for="item in groupItem.children"
            :key="item.id"
            :text="item.name"
            @click="selectedMenuItem(item)"
          >
            <nut-badge
              :value="
                state.isEdit
                  ? state.homepageMenuList
                      .map((m) => {
                        return m.id;
                      })
                      .includes(item.id)
                    ? ''
                    : '+'
                  : unreadCount(getMenuItemBadgeValue(item.forword))
              "
              :color="state.isEdit ? '#27c530' : '#ff3e3e'"
            >
              <nut-avatar shape="square" bg-color="transparent">
                <image :src="getSysImgUrl(item.imgBase64, true)" />
              </nut-avatar>
            </nut-badge>
          </nut-grid-item>
        </nut-grid>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index-v2.scss';
</style>
